package com.example.android.jmatt.acc;

import java.io.IOException;
import java.io.InputStream;

import android.util.Log;

public class FileReaderFactory {

    private static int MAX_FILE_SIZE = 300 * 1024;
    
    public static InputStream getNextStream() {
        int fileSize = (new Double(Math.random() * MAX_FILE_SIZE)).intValue();
        Log.d("JMATT", "Creating file of size " + fileSize);
        return new FakeIncomingStream(fileSize);
    }
    
    private static class FakeIncomingStream extends InputStream {

        private int mDelay = 30;
        private int mSize;
        private int bytesRead = 0;
        private static final int BYTE_SIZE = 8 * 1024;
        private static final int PAUSE_SIZE = 1024 * 16;
        
        public FakeIncomingStream(int size) {
            mSize = size;
        }
        
        /**
         * 
         * @param size The total size of the stream to read
         * @param delay The length of time to pause after reading each 512 bytes
         */
        public FakeIncomingStream(int size, int delay) {
            mSize = size;
            mDelay = delay;
        }
        
        @Override
        public int read() throws IOException {
            byte[] output = new byte[1];
            int endCheck = read(output);
            return endCheck == -1 ? endCheck : output[0];
        }
        
        @Override
        public int read(byte[] buffer) {
            return read(buffer, 0, buffer.length);
        }
        
        @Override
        public int read(byte[] buffer, int offset, int length) {
            if (bytesRead >= mSize) {
                return -1;
            }
            
            int bytesToReturn = length <= BYTE_SIZE ? length : BYTE_SIZE;
            int count = 0;
            
            for (; count < bytesToReturn && bytesRead < mSize; count++) {
                buffer[offset + count] = (new Double(Math.random() * 255 - 128)).byteValue();
                
                if ((bytesRead + 1) % PAUSE_SIZE == 0) {
                    try {
                        Thread.sleep((new Double(Math.random() * mDelay)).intValue());
                    } catch (InterruptedException e) {
                        
                    }
                }
                bytesRead++;
            }
            return count;
        }
    }
    
}
